import { BinaryToTextEncoding, createHash } from 'crypto'

export const hashString = (source: string, encoding: BinaryToTextEncoding = 'hex', length?: number) => {
  const hash = createHash('sha1').update(source).digest(encoding)
  return length ? hash.slice(0, length).padStart(length, '_') : hash
}

export const escape = (str: string) => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')

export const toArray = <T = any>(data: any): T[] => {
  if (Array.isArray(data)) return data
  if (data == null) return []
  if (typeof data !== 'object') return [data]
  if (Symbol.iterator in data || 'length' in data) return Array.from(data as any)
  return [data]
}
export const toBuffer = (value: Buffer | Parameters<typeof Buffer['from']>[0]) => {
  if (Buffer.isBuffer(value)) return value
  return Buffer.from(value)
}

export const getResolveUrl = (path: string, URL = 'URL') => `new ${URL}(${path}).href`

export const getRelativeUrlFromDocument = (relativePath: string, umd = false) =>
  getResolveUrl(
    `${JSON.stringify(relativePath)}, ${
      umd ? `typeof document === 'undefined' ? location.href : ` : ''
    }document.currentScript && document.currentScript.src || document.baseURI`
  )

export const getUrlFromDocument = (chunkId: string, umd = false) =>
  `${
    umd ? `typeof document === 'undefined' ? location.href : ` : ''
  }(document.currentScript && document.currentScript.src || new URL(${JSON.stringify(chunkId)}, document.baseURI).href)`

export const isVirtual = (source: string) => {
  return /[\0\?]/.test(source)
}
